package com.CGFrame.gantt;

import java.awt.Color;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;

import javax.swing.JApplet;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.data.category.IntervalCategoryDataset;
import org.jfree.data.gantt.Task;
import org.jfree.data.gantt.TaskSeries;
import org.jfree.data.gantt.TaskSeriesCollection;

import com.CGFrame.struts.POJOs.Make;
import com.CGFrame.struts.POJOs.Project;
import com.CGFrame.struts.POJOs.Shot;
import com.CGFrame.struts.POJOs.Shotgroup;
import com.CGFrame.struts.bean.ProjectOperate;
import com.CGFrame.struts.bean.ProjectOperateFactory;
import com.CGFrame.struts.bean.keypath.KeypathBean;
import com.CGFrame.struts.bean.keypath.EventNode;

public class ShotGantt extends JApplet implements Gantt{

	Project project ;
//	boolean showMake = false; 
	StringBuffer ids = new StringBuffer(); //���category ���� �� ID
	static { System.setSecurityManager(null); } //��ʹ�ð�ȫ������
	public void init()
	{
		String projectId = getParameter("projectId");
		ProjectOperate pop = ProjectOperateFactory.getprojectOperate();
		this.project = (Project)pop.UniqueQuery("Project", "projectId,"+1);
		drawChart(null,null);
		
	}
	
	public void drawChart(String type ,String id)
	{
		
		this.ids = new StringBuffer();
		
		IntervalCategoryDataset dataset = createDateSet(type,id);
		JFreeChart chart = createChart(dataset);
		CategoryPlot plot = (CategoryPlot) chart.getPlot();
		//      plot.getDomainAxis().setMaxCategoryLabelWidthRatio(10.0f);
		plot.setNoDataMessage("��ǰû�о�ͷ");
//		  plot.setOrientation(PlotOrientation.HORIZONTAL);
//		  plot.addChangeListener();
		CategoryItemRenderer renderer = plot.getRenderer();
		renderer.setSeriesPaint(0, Color.blue);
		renderer.setSeriesPaint(1, Color.darkGray);
		renderer.setItemURLGenerator( new CustomCategoryURLGenerator(ids));
	//	renderer.setToolTipGenerator(new CustomGanttToolTips(ids) );
		// add the chart to a panel...
		
		
		
		final ChartPanel chartPanel = new ChartPanel(chart);
//		chartPanel.setPreferredSize(new java.awt.Dimension(500, 20*number));
		chartPanel.addChartMouseListener(new MouseListener(this));
/*
		JButton showButton = new JButton("OK");
		showButton.setActionCommand("showMake");
		showButton.addActionListener(this);
		chartPanel.add(showButton);
		
*/	
		setContentPane(chartPanel);
		validate();
	}
	
	IntervalCategoryDataset createDateSet(String type ,String id)
	{
		TaskSeries s1 = new TaskSeries("�ƻ�ʱ��");
		Iterator ite_ShotGroups = project.getShotgroups().iterator();
		while (ite_ShotGroups.hasNext())
		{
			Shotgroup sGroup = (Shotgroup)ite_ShotGroups.next();
			Iterator ite_Shots = sGroup.getShots().iterator();
			while( ite_Shots.hasNext())
			{
				Shot shot = (Shot)ite_Shots.next();
				Integer shotId = shot.getShotId();
				Date startTime = shot.getPlanStartTime();
				Date endTime   = shot.getPlanEndTime();
				if (startTime !=null && endTime !=null)
				{
					startTime.setHours(8);
					endTime.setHours(18);
					String shotName = shot.getShotName();
					Task sTask = null;
//					System.out.println("Ԫ��"+elementName+":"+startTime.toString()+"-->"+endTime.toString());
					try
					{
						sTask = new Task("��ͷ:"+shotName,startTime,endTime);
						
					}
					catch(Exception e)
					{
						System.out.println(shotName+".."+e);
						continue;
					}
//					System.out.println("end");
					String status = shot.getStatus().getStatusName(); 
					if(status.equals("�����"))
					{
						sTask.setPercentComplete(1);					
					}
					else if (status.equals("��¼��"))
					{
						sTask.setPercentComplete(0);
					}
					else if (status.equals("�ȴ�ȷ��"))
					{
						sTask.setPercentComplete(0.5);
					}
					s1.add(sTask);
					ids.append("shot,"+shotId+";");
					
					//add Make  ѡ�־�ͷ�򻭳����������
					try
					{
						if (type.equals("shot") && id.equals(shotId.toString())) 
						{
							
							KeypathBean keyPathBean = new KeypathBean();
							EventNode[] makes = keyPathBean.Init(shot, "Shot");
							int length = makes.length;
							for (int i = 0; i < length; i++) {
								ProjectOperate pop = ProjectOperateFactory.getprojectOperate();
								int makeId = makes[i].getId();
								int makeVe = makes[i].getVe();
								Make make = (Make) pop.UniqueQuery("Make",
										"makeId," + makeId);
								// System.out.println(make.getMakeName());
								// System.out.println(makes[i].getVe());
								// System.out.println(makes[i].getVl());
								String makeName = make.getMakeName();
								int lastTime = make.getExceptHours();
								Date makeSTime = this.dateAddHour(startTime,
										makeVe);
								Date makeETime = this.dateAddHour(startTime,
										makeVe + lastTime);
								// System.out.println(makeSTime.toString()+"-->"+makeETime.toString());
								Task mTask = null;
								try {
									mTask = new Task("����:" + makeName,
											makeSTime, makeETime);
								} catch (Exception e) {
									System.out.println(make.getMakeName()
											+ "..����.." + e);
									continue;
								}
								// System.out.println(make.getMakeId()+make.getMakeName()+"addend");

								s1.add(mTask);
								ids.append("make," + makeId + ";");
							}
						} // end  if (type.equals("shot") && id.equals(shotId.toString())) 
					
					}
					catch (Exception e)
					{
					//	System.out.println("ûѡ");
					}
					
					
				}// end of  startTime !=null && endTime !=null
				else //startTime endTime û�趨
				{
					Date nowTime = new Date();
					Task eTask = new Task(shot.getShotName(),nowTime,nowTime);
					s1.add(eTask);
					ids.append("shot,"+shot.getShotId()+";");
				}
			}
		}
		
		TaskSeriesCollection collection = new TaskSeriesCollection();
        collection.add(s1);

        return collection;
	}
	
	JFreeChart createChart(final IntervalCategoryDataset dataset) {
        final JFreeChart chart = ChartFactory.createGanttChart(
            null,  // chart title
            "��ͷ",              // domain axis label
            "����",              // range axis label
            dataset,             // data
            true,                // include legend
            true,                // tooltips
            true                // urls
        );    
//        chart.getCategoryPlot().getDomainAxis().setMaxCategoryLabelWidthRatio(10.0f); 

   //     chart.addSubtitle(new TextTitle("��ɫ:�����", new Font("����", Font.BOLD,12)));
   //     chart.addSubtitle(new TextTitle("��ɫ:δ���", new Font("����", Font.BOLD,12)));
        return chart;    
    }
	
	Date dateAddHour(Date date , int totalHour)//�����ĩ
	{
		int day = totalHour/8;
		int hour = totalHour%8;
		GregorianCalendar  cal = new GregorianCalendar();
		cal.setTime(date);
		int dayOfWeek1 = cal.get(Calendar.DAY_OF_WEEK); //�ܼ�
//		System.out.println("1�����յģ��������ܼ���"+dayOfWeek1);
		if (dayOfWeek1 == 1 )cal.add(GregorianCalendar.DATE, 1);
		if (dayOfWeek1 == 7 )cal.add(GregorianCalendar.DATE, 2);
		for (int i = 1 ; i<=day ; i++)
		{
			cal.add(GregorianCalendar.DATE, 1);
			int dayOfWeek2 = cal.get(Calendar.DAY_OF_WEEK); //��1����ܼ�
//			System.out.println("1�����յģ�����һ����������ܼ���"+dayOfWeek2);
			if (dayOfWeek2 == 7 )cal.add(GregorianCalendar.DATE, 2); //�������ټ�2��
		}
		cal.add(GregorianCalendar.HOUR, hour);
		int dayOfWeek3 = cal.get(Calendar.DAY_OF_WEEK); //��hour���ܼ�
		if (dayOfWeek3 == 7 )cal.add(GregorianCalendar.DATE, 2); //�������ټ�2��
		return cal.getTime();
	}
/*
	public void actionPerformed(ActionEvent actionEvent) {
		// TODO Auto-generated method stub
		if (actionEvent.getActionCommand().equals("showMake"))
		{
			System.out.println("..showMake");
			this.showMake = !(this.showMake);
			this.setVisible(false);
			drawChart();
			this.setVisible(true);
			
		}
	}
*/	
	public StringBuffer getIds()
	{
		return ids;
	}
	
}
